//
//  HomeView.swift
//  xgwjinterconnection
//
//  Created by WangWeiShuo on 2025/8/13.
//

import SwiftUI
import Combine

struct HomeView: View {
    @StateObject private var socketManager = SocketManager.shared
    @State private var vehicleInfo: VehicleInfoBean?
    @State private var cancellables = Set<AnyCancellable>()
    // 用于存储定时器订阅
    @State private var cancellable: AnyCancellable?
    // 控制定时器状态
    @State private var isRunning: Bool = false
    @State private var isConnected: Bool = false
    
    var body: some View {
        VStack(alignment: .leading,spacing: 0) {
            
            // 顶部区域：标题
            HStack {
                Text(vehicleInfo?.vehtype ?? "DIRECT-d46-101")
                    .font(.title2)
                    .foregroundColor(.white)
                
                Spacer()
                
            }.padding(.leading)
                .frame(maxHeight: 65)
                .background(
                    Image("bg_titlebar")
                        .resizable()
                        .edgesIgnoringSafeArea(.all)
                )
            
            VStack{
                HStack {
                    Text(vehicleInfo?.gear ?? "N0")
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(.black)
                    
                    Spacer()
                    
                    //故障警示、网络状态图标
                    Image(systemName: "exclamationmark.triangle")
                        .foregroundColor(.yellow)
                        .font(.title)
                    
                    Image(systemName: "wifi")
                        .foregroundColor(isConnected ? .green: .red)
                        .font(.title)
                }.padding()
                
                
                // 挖掘机图片展示
                Image("bg_wj")
                    .resizable()
                    .scaledToFit()
                    .frame(maxWidth: .infinity)
                    .padding()
                
                // 状态信息行：燃油、温度、水位
                HStack(spacing: 0) {
                    StatusItemView(icon: "icon_oil", value: vehicleInfo?.fuel ?? "0", valueColor: textColor(numberString: vehicleInfo?.fuel ?? "0",baseNumber: 10,isReverse: false),unit: "%")
                        .frame(maxWidth: .infinity)
                    
                    Divider()
                        .frame(height: 40)
                        .padding(.vertical, 5)
                    
                    StatusItemView(icon: "icon_temperature", value: vehicleInfo?.temperature ?? "-40", valueColor: textColor(numberString: vehicleInfo?.temperature ?? "0",baseNumber: 105,isReverse: true),unit: "°C")
                        .frame(maxWidth: .infinity)
                    
                    Divider()
                        .frame(height: 40)
                        .padding(.vertical, 5)
                    
                    StatusItemView(icon: "icon_driver", value: vehicleInfo?.urea ?? "0", valueColor:textColor(numberString: vehicleInfo?.urea ?? "0", baseNumber: 10, isReverse: false),unit: "%")
                        .frame(maxWidth: .infinity)
                }.padding(10)
            }.background(Color("color_gray_f3f3f3"))
            
            
            // 功能按钮区：故障报警、运行信息、机器信息
            HStack(spacing: 20) {
                NavigationLink(){
                    FaultAlarmView()
                }label: {
                    FunctionEnterView(title: NSLocalizedString("fault_info", comment: "故障报警"), imageName: "bg_alarm")
                }
                
                
                NavigationLink(){
                    WorkingView()
                }label: {
                    
                    FunctionEnterView(title: NSLocalizedString("working_info", comment: "运行信息"), imageName: "bg_setting")
                }
                
                
                NavigationLink(){
                    MachineVersionView()
                }label: {
                    FunctionEnterView(title: NSLocalizedString("vehicle_info", comment: "机器信息"), imageName: "bg_info")
                }
            }
            .padding()
            
            Spacer()
            
        }
        .onAppear {
            // 订阅用户信息消息
            socketManager.subscribeToVehicleInfo()
                .receive(on: DispatchQueue.main)
                .sink {  info in
                    vehicleInfo = info
                }
                .store(in: &cancellables)
            SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_VEHICLE_INFO)
            startTimer()
        }
        .onDisappear{
            stopTimer()
        }
    }
    
    // 启动定时器
    private func startTimer() {
        isRunning = true
        // 创建定时器：每隔1秒发送一次信号，在主线程接收
        cancellable = Timer.publish(every: 5, on: .main, in: .common)
            .autoconnect()
            .sink { _ in
                // 每秒执行的任务
                print("定时器执行")
                isConnected = socketManager.state == .connected
                SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_VEHICLE_INFO)
            }
    }
    
    // 停止定时器
    private func stopTimer() {
        isRunning = false
        cancellable?.cancel() // 取消订阅
        cancellable = nil
    }
    
    // 根据数值大小决定文字颜色
    private func textColor(numberString: String,baseNumber: Double,isReverse:Bool) -> Color {
            // 尝试将字符串转换为Double类型
            guard let number = Double(numberString) else {
                return .gray // 转换失败时显示灰色
            }
            
            if number <= baseNumber {
                if(isReverse){
                    return .blue
                }else{
                    return .red
                }
            } else {
                if(isReverse){
                    return .red
                }else{
                    return .blue
                }
            }
        }
    
}

// 状态信息子View：燃油、温度、水位等一行展示
struct StatusItemView: View {
    let icon: String
    let value: String
    let valueColor: Color
    let unit: String
    
    var body: some View {
        VStack {
            Image(icon).resizable().frame(maxWidth: 30,maxHeight: 30)
            
            HStack{
                Text(value)
                    .font(.title2)
                    .foregroundColor(valueColor)
                Text(unit)
                    .font(.title2)
                    .foregroundColor(.black)
            }
            
        }
    }
}

// 功能按钮子View：故障报警、运行信息、机器信息等
struct FunctionButtonView: View {
    let title: String
    let imageName: String
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            VStack{
                VStack {
                    Image(imageName).resizable().frame(maxWidth: 50,maxHeight: 50)
                }
                .frame(maxWidth: 80,maxHeight: 70)
                .padding()
                .background(Color.gray.opacity(0.1))
                .cornerRadius(8)
                
                
                Text(title)
                    .font(.subheadline)
                    .foregroundColor(.black)
            }
        }
    }
}

struct FunctionEnterView: View {
    let title: String
    let imageName: String
    
    var body: some View {
        VStack{
            VStack {
                Image(imageName).resizable().frame(maxWidth: 50,maxHeight: 50)
            }
            .frame(maxWidth: 80,maxHeight: 70)
            .padding()
            .background(Color.gray.opacity(0.1))
            .cornerRadius(8)
            
            
            Text(title)
                .font(.subheadline)
                .foregroundColor(.black)
            
        }
    }
}

#Preview {
    HomeView()
}
